<template>
  <div class="countdown-page">
    <div class="countdown-header">
      <n-button round type="info" @click="$router.push('/')"
        >← 返回首页</n-button
      >
      <h1>专注倒计时</h1>
    </div>

    <div class="countdown-container">
      <!-- 修复倒计时显示区域 -->
      <div class="countdown-display">
        <!-- 移除函数调用语法，直接使用 computed 属性 -->
        <div class="time-digit">{{ formatTime }}</div>
      </div>

      <!-- 时间设置区域 -->
      <div class="time-setting">
        <div class="time-input-group">
          <div class="time-input-item">
            <n-input-number
              v-model:value="hours"
              min="0"
              max="23"
              @input="updateTime"
              placeholder="时"
            />
          </div>
          <span class="colon">:</span>
          <div class="time-input-item">
            <n-input-number
              v-model:value="minutes"
              min="0"
              max="59"
              @input="updateTime"
              placeholder="分"
            />
          </div>
          <span class="colon">:</span>
          <div class="time-input-item">
            <n-input-number
              v-model:value="seconds"
              min="0"
              max="59"
              @input="updateTime"
              placeholder="秒"
            />
          </div>
        </div>
      </div>

      <!-- 控制按钮区域 -->
      <div class="control-buttons">
        <n-button
          type="success"
          class="control-btn start-btn"
          @click="startCountdown"
          :disabled="isRunning || remainingTime <= 0"
        >
          开始
        </n-button>
        <n-button
          type="danger"
          class="control-btn pause-btn"
          @click="pauseCountdown"
          :disabled="!isRunning"
        >
          暂停
        </n-button>
        <n-button type="error" class="control-btn reset-btn" @click="resetCountdown">
          重置
        </n-button>
      </div>

      <!-- 预设时间区域 -->
      <div class="preset-times">
        <n-button
          type="info"
          v-for="preset in presetTimes"
          :key="preset.value"
          @click="setPresetTime(preset.value)"
        >
          {{ preset.label }}
        </n-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted, computed } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { sendNotification } from "@tauri-apps/plugin-notification";
import { NButton, NInputNumber } from "naive-ui";

// 时间状态
const hours = ref(0);
const minutes = ref(25); // 默认25分钟（番茄工作法时长）
const seconds = ref(0);
const remainingTime = ref(
  hours.value * 3600 + minutes.value * 60 + seconds.value
);
const isRunning = ref(false);
let countdownInterval = null;

// 预设时间选项
const presetTimes = [
  { label: "5分钟", value: 300 },
  { label: "15分钟", value: 900 },
  { label: "25分钟", value: 1500 },
  { label: "50分钟", value: 3000 },
];

// 格式化时间显示（HH:MM:SS）
// 此 computed 属性已正确依赖 remainingTime，会自动更新
const formatTime = computed(() => {
  const totalSeconds = remainingTime.value;
  const h = Math.floor(totalSeconds / 3600)
    .toString()
    .padStart(2, "0");
  const m = Math.floor((totalSeconds % 3600) / 60)
    .toString()
    .padStart(2, "0");
  const s = (totalSeconds % 60).toString().padStart(2, "0");
  return `${h}:${m}:${s}`;
});

// 更新剩余时间
function updateTime() {
  const h = Number(hours.value) || 0;
  const m = Number(minutes.value) || 0;
  const s = Number(seconds.value) || 0;

  // 限制分钟和秒的最大值
  const validM = Math.min(Math.max(m, 0), 59);
  const validS = Math.min(Math.max(s, 0), 59);

  minutes.value = validM;
  seconds.value = validS;
  remainingTime.value = h * 3600 + validM * 60 + validS;
}

// 开始倒计时
function startCountdown() {
  if (isRunning.value || remainingTime.value <= 0) return;

  isRunning.value = true;
  countdownInterval = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(countdownInterval);
      isRunning.value = false;
      // 倒计时结束时触发系统通知
      const params = {
        title: "倒计时结束",
        body: "您的专注时间已结束！",
        icon: "none",
      };
      invoke("show_notification", { params: params }).catch((err) =>
        console.error("Notification error:", err)
      );
      // 播放提示音
      invoke("play_sound")
        .then(() => console.log("Sound played successfully"))
        .catch((err) => console.error("Sound playback error:", err));
    }
  }, 1000);
}

// 暂停倒计时
function pauseCountdown() {
  if (!isRunning.value) return;

  clearInterval(countdownInterval);
  isRunning.value = false;
}

// 重置倒计时
function resetCountdown() {
  pauseCountdown();
  updateTime(); // 重新计算时间（使用当前输入的时分秒）
}

// 设置预设时间
function setPresetTime(totalSeconds) {
  pauseCountdown();
  hours.value = Math.floor(totalSeconds / 3600);
  minutes.value = Math.floor((totalSeconds % 3600) / 60);
  seconds.value = totalSeconds % 60;
  remainingTime.value = totalSeconds;
}

// 组件卸载时清理定时器
onUnmounted(() => {
  clearInterval(countdownInterval);
});
</script>

<style scoped>
.countdown-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 2rem;
  box-sizing: border-box;
}

.countdown-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
}

.back-button {
  padding: 0.5rem 1rem;
  background-color: #f0f0f0;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.back-button:hover {
  background-color: #e0e0e0;
}

.countdown-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2rem;
}

.countdown-display {
  background: linear-gradient(135deg, #646cff 0%, #396cd8 100%);
  border-radius: 16px;
  padding: 2rem 4rem;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.time-digit {
  font-size: 5rem;
  font-weight: bold;
  color: white;
  font-family: "Courier New", monospace;
  letter-spacing: 4px;
}

.time-setting {
  width: 100%;
  max-width: 400px;
}

.time-input-group {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
}

.time-input-item {
  width: 30%;
}

.time-input-item input {
  width: 100%;
  padding: 0.8rem;
  font-size: 1.2rem;
  text-align: center;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.colon {
  font-size: 2rem;
  font-weight: bold;
  color: #666;
}

.control-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.control-btn {
  padding: 0.8rem 2rem;
  font-size: 1.1rem;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.start-btn {
  background-color: #4caf50;
  color: white;
}

.pause-btn {
  background-color: #ff9800;
  color: white;
}

.reset-btn {
  background-color: #f44336;
  color: white;
}

.control-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.preset-times {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 0.8rem;
  margin-top: 2rem;
}

.preset-btn {
  padding: 0.5rem 1rem;
  border-radius: 20px;
  border: 1px solid #646cff;
  background: transparent;
  color: #646cff;
  cursor: pointer;
  transition: all 0.2s;
}

.preset-btn:hover {
  background-color: #646cff;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .time-digit {
    font-size: 3.5rem;
  }

  .countdown-display {
    padding: 1.5rem 2rem;
  }

  .control-buttons {
    flex-direction: column;
    width: 100%;
    max-width: 300px;
  }

  .control-btn {
    width: 100%;
  }
}
</style>
